﻿@inject ILocalStorageService _localStorage
@inject IHttpService _httpService
@inject IDataCacheService _dataCacheService
@inject IPopupService PopupService


@code {

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        await base.OnAfterRenderAsync(firstRender);
        if (firstRender)
        {
            //读取数据
            var taskList = await _localStorage.GetItemAsync<List<DelayedTask>>("DelayedTasks");
            if (taskList != null)
            {
                _dataCacheService.DelayedTaskList = taskList;
            }
            //确保网络连通
            if (await _httpService.GetAsync<List<HomeNewsAloneViewModel>>("api/home/GetHomeNewsView") == null)
            {
                return;
            }

            foreach(var item in _dataCacheService.DelayedTaskList)
            {
                try
                {
                    string tipStr = $"执行任务成功，当前队列[{_dataCacheService.DelayedTaskList.IndexOf(item) + 1}/{_dataCacheService.DelayedTaskList.Count}]";
                    if (item.Type == DelayedTaskType.DrawLottery)
                    {
                        var model = JsonSerializer.Deserialize<ManualLotteryModel>(item.Context, ToolHelper.options);
                        var obj = await _httpService.PostAsync<ManualLotteryModel, Result>("api/lotteries/DrawLottery", model);
                        //判断结果
                        if (obj.Successful == false)
                        {

                            await PopupService.ToastErrorAsync(tipStr,"抽奖失败，"+ obj.Error);
                        }
                        else
                        {
                            await PopupService.ToastSuccessAsync(tipStr, "抽奖成功");
                        }
                    }

                }
                catch
                {

                }

            }

            await _localStorage.RemoveItemAsync("DelayedTasks");
        }
    }
}
